package graphic.mycomponents;

import graphic.ChatDialogPanel;

import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyledDocument;

import core.Client;

public class SingleChatPanel extends JPanel {
	
	String receiver;
	
	JScrollPane centerPane;
	JTextField chatTextField;
	
	StyledDocument chatDocumentStyle;
	Style userIdMessageStyle;
	Style logMessageStyle;
	
	public SingleChatPanel(String receiver)
	{
		super.setLayout(new BorderLayout());
	
		this.receiver = receiver;
		
		JTextPane chatPane = new JTextPane();
		chatPane.setEditable(false);
		chatPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 30, 10));
		
		this.chatDocumentStyle = chatPane.getStyledDocument();
		
		this.centerPane = new JScrollPane();
		
		this.chatTextField = new JTextField();
		this.chatTextField.addKeyListener(new KeyAdapter()
		{
			@Override
			public void keyPressed(KeyEvent e) {
				if(e.getKeyCode() == e.VK_ENTER)
				{
					if(!SingleChatPanel.this.chatTextField.getText().trim().equals(""))
					{
						Client.getInstance().sendChatMessage(SingleChatPanel.this.receiver, SingleChatPanel.this.chatTextField.getText());
						SingleChatPanel.this.chatTextField.setText("");
					}				
				} else if(e.getKeyCode() == e.VK_ESCAPE)
					ChatDialogPanel.getIstance().closeChat(SingleChatPanel.this.receiver);
			}
		});
		
		super.add(this.centerPane, BorderLayout.CENTER);
		super.add(this.chatTextField, BorderLayout.SOUTH);
		
		this.centerPane.getViewport().add(chatPane);
	}

	public void writeChatMessage(String writer, String msg)
	{   
		try {
			this.chatDocumentStyle.insertString( this.chatDocumentStyle.getLength(), writer + ": ", this.userIdMessageStyle );
			this.chatDocumentStyle.insertString( this.chatDocumentStyle.getLength(), msg  + "\n", this.logMessageStyle );
			
			JScrollBar scrollBar = this.centerPane.getVerticalScrollBar();
			scrollBar.setValue(scrollBar.getMaximum());
			scrollBar.revalidate();
			scrollBar.repaint();

		} catch (BadLocationException e) {}
	}
	
}
